'use strict';

const ms = require('ms');

module.exports = {
  async createToken(data) {
    const { app } = this;
    let token = await app.jwt.sign({ data: data }, app.config.jwt.secret, { expiresIn: app.config.jwt.exp });
    let result = await this.verifyToken(token);
    return token;
  },
  async verifyToken(value) {
    const { ctx } = this;
    let token
    if (value) {
      token = value
    } else {
      token = ctx.headers.authorization || '';
      token = token.replace(/^Bearer\s+?/, '');
    }
    if (!token) {
      ctx.status = 401;
    }
    let result = await ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
    this.ctx.state.user = result;
    return result;
  },
  async jwt() {
    let result = await this.verifyToken();
    if (result) {
      let status = Date.now() + ms('2d') >= result.exp * 1000;
      if(status) {
        const newToken = await this.createToken(result.data);
        this.ctx.set('Authorization', 'Bearer ' + newToken);
        this.ctx.set('Authorization-Exp', this.ctx.state.user.exp);
      }
    }
  }
}
